package com.zt.rongda.customer.controller;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zt.rongda.customer.model.Customer;
import com.zt.rongda.customer.service.CustomerService;
import com.zt.servlet.ReqBean;
import com.zt.servlet.RequestAttribute;
import com.zt.servlet.Response;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/query")
    @ResponseBody
    public JSONObject query(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(customerService.getTable(reqBean));
    }
    
    @RequestMapping(value = "/list")
    @ResponseBody
    public JSONObject list(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(customerService.getList());
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    public JSONObject add(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        customerService.add(getCustomer(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public JSONObject update(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        customerService.update(getCustomer(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public JSONObject delete(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        customerService.delete(reqBean.getInfo("customerId"));
        return Response.responseSuccess();
    }

    /**
    * 从表单获取对象
    *
    * @param reqBean
    * @return
    */
    private Customer getCustomer(ReqBean reqBean) {
        Customer customer = new Customer();
        customer.setCustomerId(reqBean.getInfo("customerId"));
        customer.setCustomerName(reqBean.getInfo("customerName"));
        customer.setContactsName(reqBean.getInfo("contactsName"));
        customer.setContactsPhone(reqBean.getInfo("contactsPhone"));
        customer.setAddress(reqBean.getInfo("address"));
        customer.setSettlementType(reqBean.getInfo("settlementType"));
        customer.setOperator(reqBean.getUserId());
        customer.setRemark(reqBean.getInfo("remark"));
        return customer;
    }

}